package com.rdxer.api;

import com.rdxer.core.entity.Result;
import com.rdxer.core.entity.StatusCode;
import com.rdxer.core.exception.exceptions.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/// 捕获控制器异常
@ControllerAdvice
public class RestExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(RestExceptionHandler.class);

    @ExceptionHandler({BaseException.class})
    @ResponseBody
    public ResponseEntity<Result> handleRequest(BaseException e, WebRequest request) {
        e.printStackTrace();
        logger.warn(">>【"+e.getCode() + "】:" + e.getMessage() +"<<");
        ResponseEntity<Result> body = ResponseEntity.status(e.getHttpCode()).body(new Result(false, e.getCode(), "" + e.getMessage()));
        return body;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleValidExcetionRequest(MethodArgumentNotValidException ex){
        ex.printStackTrace();

        FieldError fieldError = ex.getBindingResult().getFieldError();
        logger.info("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        Map<String,String> data = new HashMap<String,String>();

        for (FieldError error : fieldErrors) {
            data.put(error.getField(),error.getDefaultMessage());
        }

        Result result = new Result(false, StatusCode.ParameterErr, String.format("参数异常[x%s]:(%s)%s", fieldErrors.size(),fieldError.getField(),fieldError.getDefaultMessage()));

        result.setData(data);

        return result;
    }

//    @ExceptionHandler(BindException.class)
//    public Map<String,Object> handleBindException(BindException ex) {
//        //校验 除了 requestbody 注解方式的参数校验 对应的 bindingresult 为 BeanPropertyBindingResult
//        FieldError fieldError = ex.getBindingResult().getFieldError();
//        log.info("必填校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
//        Map<String,Object> result = new HashMap<String,Object>();
//        result.put("respCode", "01002");
//        result.put("respMsg", fieldError.getDefaultMessage());
//        return result;
//    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleAllRequest(Exception e){
        e.printStackTrace();
        return new Result(false, StatusCode.ERROR, "异常:"+e.getMessage());
    }
}
